package siteflash.controller;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import siteflash.data.SiteFlashPersistenceManage;
import siteflash.model.ListGame;
import siteflash.model.PageCron;
import siteflash.model.Tag;

public class Cron extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
		resp.setContentType("text/plain");
		
		PersistenceManager psm = SiteFlashPersistenceManage.get().getPersistenceManager();
		Query query = psm.newQuery(PageCron.class);
		List<PageCron> listResult = (List<PageCron>) query.execute();
		int page = 1;
		PageCron pageCron = new PageCron();
		if (listResult.size() > 0) {
			pageCron = listResult.get(0);
			page = (int) pageCron.getPage();
		}
		
		if (page <= 623) {
			String url = "http://www.y8.com/tags/1_Player/" + page + "?sort=created_at";
			String alias = "";
			String content = "";
			String message = "";
			Key k = null;
			ListGame listGame = new ListGame();
			try {
				content = General.getUrl(url);
				Document doc = Jsoup.parse(content);
				Elements thumbs = doc.select(".container").select("table td[class=menu]").select("div.thumb");
				for (int i = 0; i < thumbs.size(); i++ ) {
					listGame = null;
					alias = General.getName(thumbs.get(i).select("a").first().attr("href")); //req.getParameter("alias");
					System.out.println(alias);
					
					k = KeyFactory.createKey(ListGame.class.getSimpleName(), alias);
					try {
			        	listGame = psm.getObjectById(ListGame.class, k);
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
					
					if (listGame == null) {
						listGame = new ListGame();
						listGame.setAlias(alias);
						psm.makePersistent(listGame);
					}
					
					resp.getWriter().println("Add game success to list: "+ alias);
				}
				//Update page
				pageCron.setPage(page + 1);
				psm.currentTransaction().begin();
				psm.makePersistent(pageCron);
				psm.currentTransaction().commit();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			//Remove cache
			Cache cache = null;
			try {
		        cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		    } catch (CacheException e) {
		       e.printStackTrace();
		    }
		    if (cache.containsKey("tags")) {
		    	//cache.remove("tags");
		    }
		}
	}
}
